package com.x.erp.manage;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.x.erp.dao.CarDao;
import com.x.erp.dao.CarOutDao;
import com.x.erp.model.Car;
import com.x.erp.model.CarLog;
import com.x.erp.model.CarOut;
import com.x.erp.model.GateCar;
import com.x.erp.util.ConstantState;
import com.x.framework.manage.BaseManage;
/**
 * 道闸出入车辆信息服务
 */
@Service
public class GateCarManage extends BaseManage {
	
	@Autowired
	private CarDao carDao;// 车辆信息DAO
	
	@Autowired
	private CarOutDao carOutDao;// 临时出场车辆信息DAO

	/**
	 * 
	 * @param carAge
	 * @return
	 * @throws Exception 
	 */
	public GateCar insertGateCar(GateCar gateCar) throws Exception {
		gateCar = this.insert(gateCar);
		if(StringUtils.isNotEmpty(gateCar.getCarRfid())){
			Car selectCar = new Car();
			selectCar.setCarRfid(gateCar.getCarRfid());
			selectCar = carDao.selectCar(selectCar);
			if(selectCar != null) {
				if (gateCar.getCarState() == 1) { // 道闸车辆出入闸状态（1：入、2：出）
					selectCar.setCarSiteState(ConstantState.CAR_SITE_STATE_IN_FINISH);// 入场
					// 如果为抵押状态，为临时出厂车辆，将该车辆的临时出厂车辆表数据删除
					if(selectCar.getCarPledgeState() == ConstantState.CAR_PLEDG_STATE_PLEDGED){ // 抵押状态（300：未抵押状态、310：抵押状态）
						CarOut carOut = new CarOut();
						carOut.setCarId(selectCar.getCarId());
						carOutDao.delete(carOut);
					}
				} else {
					selectCar.setCarSiteState(ConstantState.CAR_SITE_STATE_OUT_FINISH); // 出场
					// 如果为抵押状态，即为临时出厂车辆，添加到临时出厂车辆表
					if(selectCar.getCarPledgeState() == ConstantState.CAR_PLEDG_STATE_PLEDGED){ // 抵押状态（300：未抵押状态、310：抵押状态）
						CarOut carOut = new CarOut();
						carOut.setCarId(selectCar.getCarId());
						CarOut selectCarOut = carOutDao.selectCarOut(carOut);
						carOut.setCarSiteTime(new Date());
						// 查询临时出场表是否有该车的信息
						if(selectCarOut != null){
							carOutDao.update(carOut);
						}else{
							carOutDao.insertCarOut(carOut);
						}
					}
				}
				Date cDate = new Date();
				selectCar.setCarSiteTime(cDate);
				this.update(selectCar);
				// 修改车辆状态 记录车辆日志
				CarLog carLog = new CarLog(cDate, "1", selectCar.getCarId());
				carLog.setCarLogInfo(gateCar.getCarState() == 1?"在场":"出场");
				carLog.setCarStateKey("carSiteState");
				carLog.setCarStateValue(gateCar.getCarState() == 1?ConstantState.CAR_SITE_STATE_IN_FINISH:ConstantState.CAR_SITE_STATE_OUT_FINISH);
				this.insert(carLog);
			}
		}
		return gateCar;
	}
}
